﻿using Pay.Core;
using Pay.TO;
using System;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;


namespace Pay.Distribution {
    public class AppAuthorizeAttribute : AuthorizeAttribute {
        public new string[] Roles {
            get; set;
        }
        protected override bool AuthorizeCore(HttpContextBase httpContext) {
            if (httpContext == null)
                throw new ArgumentNullException("HttpContext");
            if (!httpContext.User.Identity.IsAuthenticated || Roles == null || Roles.Length == 0) {
                httpContext.Response.StatusCode = 401;
                return false;
            }
            if (Roles.Any(httpContext.User.IsInRole))
                return true;
            return false;
        }

        public override void OnAuthorization(AuthorizationContext filterContext) {
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string actionName = filterContext.ActionDescriptor.ActionName;
            HttpContext context = HttpContext.Current;
            if (context.User != null && context.User.Identity.IsAuthenticated) {
                FormsIdentity _Identity = (FormsIdentity)context.User.Identity;
                var roles = _Identity.Ticket.UserData.ToObject<userCookie>().roles.ToArray();
                context.User = new GenericPrincipal(_Identity, roles);
                base.OnAuthorization(filterContext);
            } else {
                if (!filterContext.HttpContext.User.Identity.IsAuthenticated
                  && (!filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any()
                      && filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true).Any())) {
                    filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                    if (filterContext.HttpContext.Request.IsAjaxRequest()) {
                        filterContext.HttpContext.SkipAuthorization = true;
                        filterContext.HttpContext.Response.Clear();
                        //filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
                        var jsonResult = new JsonResult();
                        jsonResult.Data = new ResultMessage<object>((int)System.Net.HttpStatusCode.Unauthorized, "您还未登录，无法操作！");
                        jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                        jsonResult.ContentType = "application/json";
                        filterContext.Result = jsonResult;
                        filterContext.Result.ExecuteResult(filterContext.Controller.ControllerContext);
                        filterContext.HttpContext.Response.End();
                    } else {
                        filterContext.HttpContext.SkipAuthorization = true;
                        filterContext.HttpContext.Response.Clear();
                        //filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
                        HandleErrorInfo data = new HandleErrorInfo(new Exception("您还未登录，无法操作！"), (string)filterContext.RouteData.Values["controller"], (string)filterContext.RouteData.Values["action"]);
                        filterContext.Controller.ViewData.Model = data;
                        filterContext.Result = new ViewResult { ViewName = "Error", ViewData = filterContext.Controller.ViewData };
                    }
                }
            }
        }
    }
}